import {
  isNumber
} from '@/utils/util'
import axios from 'axios'

// const { Message } = ELEMENT
const disableLog = false

// create an axios instance
const service = axios.create({
  baseURL: 'http://192.168.0.173:8090' // api的base_url
  // timeout: 5000 // request timeout
  // headers: {
  //   'Content-Type': 'application/x-www-form-urlencoded'
  // }
})

// request interceptor
service.interceptors.request.use(config => {
  if (config.method === 'get' || config.method === 'delete') {
    !disableLog && console.log(`${config.url} ${config.method} 请求params`, config.params ? JSON.stringify(config.params) : '{}')
  } else {
    !disableLog && console.log(`${config.url} ${config.method} 请求body`, config.data ? JSON.stringify(config.data) : '{}')
  }
  // Do something before request is sent
  // if (store.getters.token) {
  //   config.headers['Authorization'] = getToken()
  // }
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone interceptor
service.interceptors.response.use(
  // response => response,
  /**
   * 下面的注释为通过在response里，自定义code来标示请求状态
   * 当code返回如下情况则说明权限有问题，登出并返回到登录页
   * 如想通过xmlhttprequest来状态码标识 逻辑可写在下面error中
   * 以下代码均为样例，请结合自生需求加以修改，若不需要，则可删除
   */
  response => {
    const res = response.data
    if (!res) {
      return Promise.reject(new Error('no response data'))
    }!disableLog && console.log(`${response.config.url} ${response.config.method} 返回data：`, response.data)
    if (isNumber(response.data.code) && response.data.code !== 200) {
      // Message.error('网络异常，请稍后重新尝试')
      return Promise.reject(new Error(`error code ${response.data.code}`))
    } else {
      return response.data
    }
  },
  error => {
    console.log('err' + error) // for debug
    // Message.error('网络异常，请稍后重新尝试')
    return Promise.reject(error)
  })

export default service
